package com.xqit.ydzhkt.login.service.impl;

import com.xqit.ydzhkt.common.exception.BizException;
import com.xqit.ydzhkt.common.response.HttpResult;
import com.xqit.ydzhkt.common.response.ResultCodeEnum;
import com.xqit.ydzhkt.common.utils.WxcxUtil;
import com.xqit.ydzhkt.entity.User;
import com.xqit.ydzhkt.login.mapper.LoginMapper;
import com.xqit.ydzhkt.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by Janus on 2020/5/22
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    //用户登录
    @Override
    public HttpResult login(String username, String password, String code) {

        User user = null;
        try {
            //1.根据用户名+密码查询用户
            loginMapper.getUserByNameAndPass(username, password);
            //用户判空
            if (user == null){
                return HttpResult.failure(ResultCodeEnum.USER_IS_NULL);
            }

            //2.openid不为空，查询并返回用户信息
            String openid = user.getWxOpenid();
            if (null != openid && !"".equals(openid)){
                return HttpResult.success(loginMapper.getUserByOpenid(openid));
            }

            //3.如果未绑定，根据code获取openid绑定当前用户
            //请求微信后台拉取openid
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                         WxcxUtil.APPID + "&secret=" +
                         WxcxUtil.APPSECRET +
                         "&js_code=" + code +
                         "&grant_type=authorization_code";

            Map<String, Object> Wx = WxcxUtil.sendGetReq(url);
            String openidWx = (String) Wx.get("openid");
            String session_key = (String) Wx.get("sessionKey");
            String sessionid = (String) Wx.get("sessionid");

            //对拉取的openid判空
            if (null == openidWx || "".equals(openidWx)){
                return HttpResult.failure(ResultCodeEnum.OPENID_IS_NOT_EXIST);
            }

            //4.绑定并返回用户信息
            //绑定用户
            int i = loginMapper.bindingOpenid(username, openidWx);
            //绑定失败
            if (i != 1){
                return HttpResult.failure(ResultCodeEnum.BINDING_OPENID_ERROR);
            }

            user = loginMapper.getUserByOpenid(openidWx);
            return HttpResult.success(user);

        } catch (BizException e) {
            System.out.println(e.getErrorMsg());
        }

        return HttpResult.success(user);
    }

}
